﻿using DSPara;
using GalaSoft.MvvmLight.Threading;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using TYBase;
using TYComm_For_DSApp.IR;
using TYControl;
using TYRTUBase;

namespace TYComm_For_DSApp
{
    public partial class ViewReCheck : WindowT
    {
        private readonly int chanNo;
        private readonly Device_IR _ir;
        private readonly Device_Switch _swi;
        private readonly OffsetPara offsetPara;
        private ViewModelBatteryTest vm = new ViewModelBatteryTest();

        public ViewReCheck(int chanNo,
            Device_IR ir,
            Device_Switch swi,
            OffsetPara offsetPara)
        {
            InitializeComponent();
            this.DataContext = vm;
            this.chanNo = chanNo;
            this._ir = ir;
            this._swi = swi;
            this.offsetPara = offsetPara;
            this.Loaded += ViewReCheck_HK_Loaded;
        }

        private void ViewReCheck_HK_Loaded(object sender, RoutedEventArgs e)
        {
            if (offsetPara == null)
            {
                cBoxOffset.IsEnabled = false;
            }
            if (_ir != null)
            {
                vm.SpeedIndex = (int)_ir.Spd;
            }
            vm.ListChan.Clear();
            for (int i = 0; i < chanNo; i++)
            {
                vm.ListChan.Add(new ChanModel { ChanNo = i + 1, IsSelected = true });
            }
            IntiDataGrid();
        }

        private Thread thread;
        private bool isStart = false;

        private bool isFirst = true;

        private void IntiDataGrid()
        {
            vm.ListIRData.Clear();
            {
                ChanIRDataModel irData = new ChanIRDataModel();
                for (int i = 0; i < chanNo; i++)
                {
                    //vm.ListChan.Add(new ChanModel { ChanNo = i + 1, });
                    irData.ListData.Add($"ocv");
                    if (isFirst == true)
                    {
                        DataGridTextColumn dgt = new DataGridTextColumn();
                        dgt.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
                        dgt.Binding = new Binding($"ListData[{2 * i}]");
                        dg.Columns.Add(dgt);
                    }

                    irData.ListData.Add($"ir");
                    if (isFirst == true)
                    {
                        DataGridTextColumn dgt = new DataGridTextColumn();
                        dgt.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
                        dgt.Binding = new Binding($"ListData[{2 * i + 1}]");
                        dg.Columns.Add(dgt);
                    }
                }
                vm.ListIRData.Add(irData);
                isFirst = false;
            }
        }

        private AutoResetEvent resetEvent = new AutoResetEvent(false);

        private void BtnClickStartCheck(object sender, RoutedEventArgs e)
        {
            if (vm.ListChan.Count(x => x.IsSelected == true) == 0)
            {
                MessageBox.Show("请选择通道号");
                return;
            }

            if (isStart == false)
            {
                isStart = true;
                IntiDataGrid();
                if (vm.CheckTime > 100)
                    vm.CheckTime = 100;
                int checkIntervel = vm.CheckIntervel;
                int testDelay = vm.TestDelay;
                int checkTimes = vm.CheckTime;
                bool offset = vm.IsUseOffset;
                List<bool> listIsSelected = new List<bool>();
                foreach (var item in vm.ListChan)
                {
                    listIsSelected.Add(item.IsSelected);
                }
                thread = new Thread(() =>
                 {
                     int times = 0;
                     while (isStart && times++ < checkTimes)
                     {
                         resetEvent.WaitOne(checkIntervel);
                         if (isStart == false)
                             return;
                         ChanIRDataModel chanIRDataModel = new ChanIRDataModel();
                         for (int i = 0; i < chanNo && i < listIsSelected.Count; i++)
                         {
                             if (isStart == false)
                                 return;
                             if (listIsSelected[i])
                             {
                                 if (_swi.SwitchTo(i + 1))
                                 {
                                     if (isStart == false)
                                         return;
                                     resetEvent.WaitOne(testDelay);
                                     if (isStart == false)
                                         return;


                                     if (_ir.ReadData(out string data))
                                     {
                                         if (_ir.DataToIR(data, out double ocv, out double ir))
                                         {
                                             if (offset && offsetPara != null)
                                             {
                                                 ocv = offsetPara.GetOCV(i + 1, ocv);
                                                 ir = offsetPara.GetIR(i + 1, ir);
                                             }
                                             chanIRDataModel.ListData.Add($"{ocv}");
                                             chanIRDataModel.ListData.Add($"{ir}");
                                         }
                                         else
                                         {
                                             chanIRDataModel.ListData.Add($"解析异常");
                                             chanIRDataModel.ListData.Add($"{data}");
                                         }
                                     }
                                     else
                                     {
                                         chanIRDataModel.ListData.Add($"读取IR异常");
                                         chanIRDataModel.ListData.Add($"");
                                     }
                                 }
                                 else
                                 {
                                     chanIRDataModel.ListData.Add($"切换通道异常");
                                     chanIRDataModel.ListData.Add($"");
                                 }
                             }
                             else
                             {
                                 chanIRDataModel.ListData.Add($"");
                                 chanIRDataModel.ListData.Add($"");
                             }
                         }
                         DispatcherHelper.UIDispatcher.Invoke(() =>
                         {
                             vm.ListIRData.Add(chanIRDataModel);
                         });
                     }
                     DispatcherHelper.UIDispatcher.Invoke(() =>
                     {
                         btnStart.IsEnabled = true;
                         btnStop.IsEnabled = false;
                     });
                     isStart = false;
                 })
                { IsBackground = true };
                thread.Start();
                btnStart.IsEnabled = false;
                btnStop.IsEnabled = true;
            }
            else
            {
                MessageBox.Show("已开始");
            }
        }

        private void BtnClickStopCheck(object sender, RoutedEventArgs e)
        {
            isStart = false;
            if (thread != null)
            {
                thread.Join();
            }
            btnStart.IsEnabled = true;
            btnStop.IsEnabled = false;
            MessageBox.Show("已停止");
        }



        private async void BtnClickExportXls(object sender, RoutedEventArgs e)
        {
            List<List<string>> list = new List<List<string>>();
            foreach (var oneData in vm.ListIRData)
            {
                List<string> listTmp = new List<string>();
                foreach (var item in oneData.ListData)
                {
                    listTmp.Add(item);
                }
                list.Add(listTmp);
            }

            //创建一个保存文件式的对话框
            SaveFileDialog sfd = new SaveFileDialog();
            //设置这个对话框的起始保存路径
            // sfd.InitialDirectory = @"D:\";
            //设置保存的文件的类型，注意过滤器的语法
            sfd.Filter = "csv|*.csv";
            sfd.FileName = $"{_ir.Spd}_{DateTime.Now.AsFileNameString()}";
            //调用ShowDialog()方法显示该对话框，该方法的返回值代表用户是否点击了确定按钮
            if (sfd.ShowDialog() == true)
            {
                string fileName = sfd.FileName;
                var ret = await Run(() =>
                  {
                      return ExcelHelper.AppendToTXT(fileName, list);
                  });
                if (ret == true)
                {
                    MessageBox.Show("导出OK");
                }
                else
                {
                    MessageBox.Show("导出失败!");
                }
            }
            else
            {
                MessageBox.Show("取消保存");
            }
        }
    }
}